package com.imut.lagain.controller;

import com.imut.lagain.common.Result;
import com.imut.lagain.entity.Notification;
import com.imut.lagain.entity.NotificationTemplate;
import com.imut.lagain.service.NotificationTemplateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

/**
 * 通知模板控制器
 */

@RestController
@RequestMapping("/notification-templates")
public class NotificationTemplateController {
    private static final Logger log = LoggerFactory.getLogger(NotificationTemplateController.class);
    @Autowired
    private NotificationTemplateService templateService;

    /**
     * 创建通知模板
     */
    @PostMapping
    public Result<NotificationTemplate> createTemplate(@RequestBody NotificationTemplate template, HttpServletRequest request) {
        try {
            Long currentUserId = getCurrentUserId(request);
            template.setCreatorId(currentUserId);
            NotificationTemplate created = templateService.createTemplate(template);
            return Result.success(created);
        } catch (Exception e) {
            log.error("创建通知模板失败", e);
            return Result.error("创建通知模板失败: " + e.getMessage());
        }
    }

    /**
     * 更新通知模板
     */
    @PutMapping("/{templateId}")
    public Result<NotificationTemplate> updateTemplate(
            @PathVariable Long templateId,
            @RequestBody NotificationTemplate template,
            HttpServletRequest request) {
        try {
            Long currentUserId = getCurrentUserId(request);
            Optional<NotificationTemplate> existing = templateService.getTemplateById(templateId);
            if (existing.isEmpty()) {
                return Result.error("模板不存在");
            }
            if (!existing.get().getCreatorId().equals(currentUserId)) {
                return Result.error("无权限修改此模板");
            }
            
            // 修复：使用正确的方法签名
            NotificationTemplate updated = templateService.updateTemplate(templateId, template);
            return Result.success(updated);
        } catch (Exception e) {
            log.error("更新通知模板失败", e);
            return Result.error("更新通知模板失败: " + e.getMessage());
        }
    }

    /**
     * 删除通知模板
     */
    @DeleteMapping("/{templateId}")
    public Result<Boolean> deleteTemplate(
            @PathVariable Long templateId,
            HttpServletRequest request) {
        try {
            log.info("检查权限：只有创建者可以删除模板");
            Long currentUserId = getCurrentUserId(request);
            Optional<NotificationTemplate> existing = templateService.getTemplateById(templateId);
            if (existing.isEmpty()) {
                return Result.error("模板不存在");
            }
            if (!existing.get().getCreatorId().equals(currentUserId)) {
                return Result.error("无权限删除此模板");
            }
            
            boolean success = templateService.deleteTemplate(templateId);
            return Result.success(success);
        } catch (Exception e) {
            log.error("删除通知模板失败", e);
            return Result.error("删除通知模板失败: " + e.getMessage());
        }
    }

    /**
     * 根据模板代码获取模板
     */
    @GetMapping("/code/{code}")
    public Result<NotificationTemplate> getTemplateByCode(@PathVariable String code) {
        try {
            Optional<NotificationTemplate> template = templateService.getTemplateByCode(code);
            if (template.isEmpty()) {
                return Result.error("模板不存在");
            }
            return Result.success(template.get());
        } catch (Exception e) {
            log.error("获取通知模板失败", e);
            return Result.error("获取通知模板失败: " + e.getMessage());
        }
    }

    /**
     * 根据微信模板ID获取模板
     */
    @GetMapping("/wechat/{wechatTemplateId}")
    public Result<NotificationTemplate> getTemplateByWechatId(@PathVariable String wechatTemplateId) {
        try {
            // 修复：使用正确的方法名
            Optional<NotificationTemplate> template = templateService.getTemplateByWechatTemplateId(wechatTemplateId);
            if (template.isEmpty()) {
                return Result.error("模板不存在");
            }
            return Result.success(template.get());
        } catch (Exception e) {
            log.error("获取通知模板失败", e);
            return Result.error("获取通知模板失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有模板
     */
    @GetMapping
    public Result<List<NotificationTemplate>> getAllTemplates() {
        try {
            // 修复：使用正确的方法名
            List<NotificationTemplate> templates = templateService.getAllEnabledTemplates();
            return Result.success(templates);
        } catch (Exception e) {
            log.error("获取所有通知模板失败", e);
            return Result.error("获取所有通知模板失败: " + e.getMessage());
        }
    }

    /**
     * 根据类型获取模板
     */
    @GetMapping("/type/{type}")
    public Result<List<NotificationTemplate>> getTemplatesByType(@PathVariable String type) {
        try {
            // 修复：将字符串转换为Notification.NotificationType枚举
            Notification.NotificationType notificationType = Notification.NotificationType.valueOf(type.toUpperCase());
            List<NotificationTemplate> templates = templateService.getTemplatesByType(notificationType);
            return Result.success(templates);
        } catch (Exception e) {
            log.error("根据类型获取通知模板失败", e);
            return Result.error("根据类型获取通知模板失败: " + e.getMessage());
        }
    }

    /**
     * 渲染模板
     */
    @PostMapping("/{templateId}/render")
    public Result<String> renderTemplate(
            @PathVariable Long templateId,
            @RequestBody Map<String, Object> data,
            HttpServletRequest request) {
        try {
            Optional<NotificationTemplate> template = templateService.getTemplateById(templateId);
            if (template.isEmpty()) {
                return Result.error("模板不存在");
            }
            
            // 修复：使用正确的方法签名
            String rendered = templateService.renderTemplate(template.get().getContent(), data);
            return Result.success(rendered);
        } catch (Exception e) {
            log.error("渲染模板失败", e);
            return Result.error("渲染模板失败: " + e.getMessage());
        }
    }

    /**
     * 构建微信数据
     */
    @PostMapping("/{templateId}/wechat-data")
    public Result<Map<String, Object>> buildWechatData(
            @PathVariable Long templateId,
            @RequestBody Map<String, Object> data) {
        try {
            Optional<NotificationTemplate> template = templateService.getTemplateById(templateId);
            if (template.isEmpty()) {
                return Result.error("模板不存在");
            }
            
            Map<String, Object> wechatData = templateService.buildWechatData(template.get(), data);
            return Result.success(wechatData);
        } catch (Exception e) {
            log.error("构建微信数据失败", e);
            return Result.error("构建微信数据失败: " + e.getMessage());
        }
    }

    /**
     * 验证模板
     */
    @PostMapping("/validate")
    public Result<Boolean> validateTemplate(@RequestBody NotificationTemplate template) {
        try {
            boolean valid = templateService.validateTemplateData(template);
            return Result.success(valid);
        } catch (Exception e) {
            log.error("验证模板失败", e);
            return Result.error("验证模板失败: " + e.getMessage());
        }
    }

    /**
     * 检查模板代码是否存在
     */
    @GetMapping("/exists/code/{code}")
    public Result<Boolean> existsByCode(@PathVariable String code) {
        try {
            boolean exists = templateService.existsByCode(code);
            return Result.success(exists);
        } catch (Exception e) {
            log.error("检查模板代码是否存在失败", e);
            return Result.error("检查模板代码是否存在失败: " + e.getMessage());
        }
    }

    /**
     * 检查微信模板ID是否存在
     */
    @GetMapping("/exists/wechat/{wechatTemplateId}")
    public Result<Boolean> existsByWechatTemplateId(@PathVariable String wechatTemplateId) {
        try {
            boolean exists = templateService.existsByWechatTemplateId(wechatTemplateId);
            return Result.success(exists);
        } catch (Exception e) {
            log.error("检查微信模板ID是否存在失败", e);
            return Result.error("检查微信模板ID是否存在失败: " + e.getMessage());
        }
    }

    /**
     * 提取模板变量
     */
    @PostMapping("/extract-variables")
    public Result<Set<String>> extractVariables(@RequestBody Map<String, String> content) {
        try {
            String templateContent = content.get("content");
            Set<String> variables = templateService.extractVariables(templateContent);
            return Result.success(variables);
        } catch (Exception e) {
            log.error("提取模板变量失败", e);
            return Result.error("提取模板变量失败: " + e.getMessage());
        }
    }

    /**
     * 预览模板
     */
    @PostMapping("/{templateId}/preview")
    public Result<Map<String, Object>> previewTemplate(
            @PathVariable Long templateId,
            @RequestBody Map<String, Object> sampleData) {
        try {
            Optional<NotificationTemplate> template = templateService.getTemplateById(templateId);
            if (template.isEmpty()) {
                return Result.error("模板不存在");
            }
            
            Map<String, Object> preview = templateService.previewTemplate(template.get(), sampleData);
            return Result.success(preview);
        } catch (Exception e) {
            log.error("预览模板失败", e);
            return Result.error("预览模板失败: " + e.getMessage());
        }
    }

    /**
     * 复制模板
     */
    @PostMapping("/{templateId}/copy")
    public Result<NotificationTemplate> copyTemplate(
            @PathVariable Long templateId,
            @RequestParam String newCode,
            @RequestParam String newName,
            HttpServletRequest request) {
        try {
            Long currentUserId = getCurrentUserId(request);
            Optional<NotificationTemplate> existing = templateService.getTemplateById(templateId);
            if (existing.isEmpty()) {
                return Result.error("源模板不存在");
            }
            
            NotificationTemplate copied = templateService.copyTemplate(templateId, newCode, newName);
            return Result.success(copied);
        } catch (Exception e) {
            log.error("复制模板失败", e);
            return Result.error("复制模板失败: " + e.getMessage());
        }
    }

    /**
     * 导入模板
     */
    @PostMapping("/import")
    public Result<List<NotificationTemplate>> importTemplates(
            @RequestBody List<NotificationTemplate> templates,
            HttpServletRequest request) {
        try {
            Long currentUserId = getCurrentUserId(request);
            // 修复：使用正确的方法签名
            List<NotificationTemplate> imported = templateService.importTemplates(templates);
            return Result.success(imported);
        } catch (Exception e) {
            log.error("导入模板失败", e);
            return Result.error("导入模板失败: " + e.getMessage());
        }
    }

    /**
     * 导出模板
     */
    @PostMapping("/export")
    public Result<List<NotificationTemplate>> exportTemplates(
            @RequestBody List<Long> templateIds,
            HttpServletRequest request) {
        try {
            Long currentUserId = getCurrentUserId(request);
            // 修复：使用正确的方法签名
            List<NotificationTemplate> exported = templateService.exportTemplates(templateIds);
            return Result.success(exported);
        } catch (Exception e) {
            log.error("导出模板失败", e);
            return Result.error("导出模板失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前用户ID
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        // 从请求中获取用户ID的逻辑
        String userIdStr = request.getHeader("X-User-Id");
        return userIdStr != null ? Long.parseLong(userIdStr) : null;
    }
}